package com.sk.coin.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.sk.coin.model.WebLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @author: SongKun
 * @date: 2021/11/24
 * @Description:
 */
@Component
@Aspect
@Order(1)
@Slf4j
public class WebLogAspect {
    /**
     * 日志记录
     * 环绕通知：方法执行之前，之后
     */

    /**
     * 定义切入点
     */
    @Pointcut("execution(* com.sk.coin.controller.*.*(..))")
    public void webLog(){
    }

    /**
     * 记录日志的环绕通知
     */
    @Around("webLog()")
    public Object recordWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = null;
        WebLog webLog = new WebLog();
        long start = System.currentTimeMillis();
        // 异常不能补货，不然全局的异常捕获会有问题
        result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end = System.currentTimeMillis();
        webLog.setSpendTime((int) (end - start)/1000);
        // 获取当前请求的request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 获取安全的上下文
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String url = request.getRequestURL().toString();
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(url);
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        webLog.setUsername(authentication==null? "anonymous": authentication.getPrincipal().toString()); // 用户Id
        webLog.setIp(request.getRemoteAddr());  // todo 获取Id地址
        // 结合Swagger注解
        // 获取方法
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        String targetClassName = proceedingJoinPoint.getTarget().getClass().getName();
        Method method = signature.getMethod();
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(annotation == null ? "no desc": annotation.value());  // 接口描述
        webLog.setMethod(targetClassName + "." + method.getName());
        webLog.setParameter(getMethodParameter(method,proceedingJoinPoint.getArgs()));  // {"key 参数的名称"： "value 参数的值"}
        webLog.setResult(result);
        log.info(JSON.toJSONString(webLog,true));
        return result;
    }

    private Object getMethodParameter(Method method,Object[] args) {
        HashMap<String, Object> map = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
        // 方法的形参名称
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            map.put(parameterNames[i],args[i]);
        }
        return map;
    }

}
